package com.huarun.common.util;

import java.security.MessageDigest;


/**
 * 生成用于微瓴后台登录的sig
 * @author eva  2018-11-01
 *
 */
public class LoginWelinkSigUtil {

    public static void main(String[] args) {
        long time = System.currentTimeMillis();
        long num = new Double(Math.random() * 1000).longValue();// 1l;
        String sig = LoginWelinkSigUtil.encrypt(Constant.WELINK_APP_KEY, time, num);
        System.out.println(time);
        System.out.println(num);
        System.out.println(sig);
    }
	
	public static String encrypt(String key,long times,long num){
        byte[] k = key.getBytes();
        byte[] t = getBytesByLong(times);
        byte[] n = getBytesByLong(num);
        byte[] np = new byte[k.length+t.length+n.length];
        int i=0;
        for(int j=0;j<k.length;j++,i++){
            np[i]=k[j];
        }
        for(int j=0;j<t.length;j++,i++){
            np[i]=t[j];
        }
        for(int j=0;j<n.length;j++,i++){
            np[i]=n[j];
        }
        String sha1 = getSHA1(np);
        return sha1;
    }

    private static byte[] getBytesByLong(long data){
        byte[] bytes = new byte[8];
        bytes[0] = (byte) (data & 0xff);
        bytes[1] = (byte) ((data >> 8) & 0xff);
        bytes[2] = (byte) ((data >> 16) & 0xff);
        bytes[3] = (byte) ((data >> 24) & 0xff);
        bytes[4] = (byte) ((data >> 32) & 0xff);
        bytes[5] = (byte) ((data >> 40) & 0xff);
        bytes[6] = (byte) ((data >> 48) & 0xff);
        bytes[7] = (byte) ((data >> 56) & 0xff);
        return bytes;
    }

    private static String getSHA1(byte[] str) {
      String sha1 = "";

      try {
          MessageDigest digest = MessageDigest.getInstance("SHA-1");
          digest.update(str);

          byte messageDigest[] = digest.digest();
          StringBuilder hexString = new StringBuilder();
          for (int i = 0; i < messageDigest.length; i++) {
              String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
              if (shaHex.length() < 2) {
                  hexString.append(0);
              }
              hexString.append(shaHex);
          }

          sha1 = hexString.toString();
      } catch (Exception e) {
          e.printStackTrace();
      }

      return sha1.toUpperCase();
  }

}
